from sqlalchemy.orm import Session
from passlib.context import CryptContext

from ..models.user import User
from ..schemas.user import RegisterRequest

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password):
    return pwd_context.hash(password)

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

# 创建用户
def create_user(db: Session, user: RegisterRequest):
    if get_user_by_email(db, user.email):
        return None
    db_user = User(email=user.email,
                   password_hash=get_password_hash(user.password))
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

# 根据ID获取用户
def get_user_by_id(db: Session, user_id: int):
    return db.query(User).filter_by(id=user_id).first()

# 根据邮箱获取用户
def get_user_by_email(db: Session, email: str):
    return db.query(User).filter_by(email=email).first()

# 获取所有用户
def get_users(db: Session, skip: int = 0, limit: int = 10):
    return db.query(User).offset(skip).limit(limit).all()

# 删除用户
def delete_user(db: Session, user_id: int):
    user = db.query(User).filter_by(id=user_id).first()
    if user:
        db.delete(user)
        db.commit()
        return True
    return False
